package com.idanchuang.component.mq.amqp.rabbit;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author yjy
 * Created at 2022/3/23 1:56 下午
 */
public class ReturnableSender {

    public static void main(String[] args) throws Exception {
        // 通过ConnectionFactory创建Connection
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername("dc_base");
        connectionFactory.setPassword("JFgs33#s3");
        connectionFactory.setHost("10.80.20.209");
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();

        // 声明交换机
        String exchange = "python-test-exchange1";
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(exchange, "direct");

        // 路由键
        String routingKey = "tester";

        // 给管道设置消息路由失败处理函数
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode,
                                     String replyText,
                                     String exchange,
                                     String routingKey,
                                     AMQP.BasicProperties properties,
                                     byte[] body)
                    throws IOException {
                System.out.println("消息路由失败，被退回来啦！ body: " + new String(body));
            }
        });

        // 发送消息
        channel.basicPublish(exchange, routingKey, true, null, "hello world1!".getBytes(StandardCharsets.UTF_8));

        Thread.sleep(3000L);
        // 结束
        connection.close();
    }

}
